package cn.wolfcode.crud.shiro;

import cn.wolfcode.crud.domain.Employee;
import cn.wolfcode.crud.mapper.EmployeeMapper;
import cn.wolfcode.crud.mapper.PermissionMapper;
import cn.wolfcode.crud.mapper.RoleMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

//继承子类
@Component//贴一个公共的方法贴
public class CrmRealm extends AuthorizingRealm {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    //权限的方法,用于权限
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //创建一个返回的权限对象
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //拿到当前登陆用户
        Employee employee =(Employee) SecurityUtils.getSubject().getPrincipal();
        //判断是否是管理员
        if (employee.isAdmin()){
            info.addRole("ADMIN");//Z自定义一个管理员
            info.addStringPermission("*:*");//给管理员统配所有权限
        }else {
            //通过id查询员工角色
            List<String> rSn =roleMapper.selectByemp(employee.getId());
            List<String> expressions = permissionMapper.selectByemp(employee.getId());
            //拿到当前用户角色放在对象中
            info.addRoles(rSn);
            //拿到当前用户权限放在对象中
            info.addStringPermissions(expressions);
        }
        return info;
    }
    @Autowired
    //用贴注解来注入bean,拿到对象
    public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher){
        super.setCredentialsMatcher(credentialsMatcher);
    }
    //认证是方法,用于登陆
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //拿到输入的名字
        String nsername =(String) authenticationToken.getPrincipal();
        //查询数据库
        Employee employee = employeeMapper.checkName(nsername);
        if (!employee.isStatus()){
            throw new AccountException();
        }
        if (employee==null){
            return null;
        }
        //身份信息可以通过工具类.getPrincipal()拿到,密码.原,renim数据源名字
        return new SimpleAuthenticationInfo(employee,employee.getPassword(),
                ByteSource.Util.bytes(employee.getName()),this.getName());
    }
}
